package gui.menubar;

import gui.MainWindow;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import model.MetroModel;
import model.readers.ReadersRegistry;

/**
 * 
 * @author Ilya Shurigyn
 *
 */
public class OpenFileMenuItem extends JMenuItem {
	
	public OpenFileMenuItem(final MainWindow parent) {
		super("Open map");
		addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(MainWindow.askForSave("Do you want to open new file without saving current?", parent)!=JOptionPane.CANCEL_OPTION);
				showOpenFileDialog(OpenFileMenuItem.this);
				parent.getMainPanel().getFirstView().afterPanelInit();
				parent.getMainPanel().getSecondView().afterPanelInit();
				
			}
			
		});
	}
	
	public static void showOpenFileDialog(Component c) {
		JFileChooser fc = new JFileChooser();
		for(ReadersRegistry.FileFormat format:ReadersRegistry.getFormats()) {
			FileFilter ff = new FileNameExtensionFilter(format.shortFileFormatDescription, format.formatFileNameExtension);			
			fc.addChoosableFileFilter(ff);
		}
		//fc.setFileFilter(fc.getChoosableFileFilters()[1]); //set default FileFilter to AndroidMap;
		
		if( fc.showOpenDialog(c) == JFileChooser.APPROVE_OPTION) {
			File f = fc.getSelectedFile();
			System.out.println(f.getName());
			MetroModel.getInstance().load(f.getAbsolutePath());
			MainWindow.modelChangedAfterLastSave = false;
		}

	}
}
